//
//  CAHomeUser.m
//  cascade-realm
//
//  Created by QSC on 30/5/24.
//

#import "CAHomeUser.h"

@implementation CAHomeUser


//获取首页用户
+ (void)getHomeUsers:(void(^)(NSArray *))success waitTime:(NSInteger)waitTime{
    
    
    NSDictionary *dic = [DBTool getData:@"homeUserIds"];
    
    if(dic[@"homeUserIds"] != nil){
        NSArray *idArray = dic[@"homeUserIds"];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(waitTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            success([self getUserFormIdArray:idArray]);
          
            [Tool HideLoading];
        });
     
        return;
    }
    
    
    NSMutableArray * idArray = [NSMutableArray array];
    
   
    
    [self getUserFormRequest:idArray userCount:12 success:^(NSArray * array) {
    
      
        [DBTool saveData:@{@"homeUserIds":array} tag:@"homeUserIds"];
        
        
        success([self getUserFormIdArray:idArray]);
        
        [Tool HideLoading];
        
        
    } failure:^{
        NSLog(@"getUserFailure");
        [Tool HideLoading];
    }];
}



//获取视频用户
+ (void)getVideoUsers:(void(^)(NSArray *))success{
    
    
    NSDictionary *dic = [DBTool getData:@"videoUserIds"];
    
    if(dic[@"videoUserIds"] != nil){
        NSArray *idArray = dic[@"videoUserIds"];
        
        NSArray * users = [self getUserFormIdArray:idArray];
       
        [self bindVideoToUser:users sucess:^{
            success(users);
        }];;
      
        [Tool HideLoading];
     
        return;
    }
    
    
    WeakSelf
    [self getHomeUsers:^(NSArray * _Nonnull users) {
        
        NSMutableArray * arr = [NSMutableArray arrayWithArray:users];
        
        [arr randomObjects];
        
        NSMutableArray *idArray = [NSMutableArray array];
        for (int i =0; i < 8; i++) {
            CAHomeUser * u = arr[i];
            [idArray addObject:u.userId];
        }

        [DBTool saveData:@{@"videoUserIds":idArray} tag:@"videoUserIds"];
        
        NSMutableArray *array = [weakSelf getUserFormIdArray:idArray];
        
        [weakSelf bindVideoToUser:array sucess:^{
            success(array);
        }];;
        
        
        
    } waitTime:0];
}

//获取视频用户
+ (void)getForumUsers:(void(^)(NSArray *))success{
    
    
    NSDictionary *dic = [DBTool getData:@"ForumUsers"];
    
    if(dic[@"ForumIds"] != nil){
        NSArray *idArray = dic[@"ForumIds"];
        
        
        success([self getUserFormIdArray:idArray]);
      
        [Tool HideLoading];
     
        return;
    }
    
    
    WeakSelf
    [self getHomeUsers:^(NSArray * _Nonnull users) {
        
        NSMutableArray * arr = [NSMutableArray arrayWithArray:users];
        
        [arr randomObjects];
        
        NSMutableArray *idArray = [NSMutableArray array];
        for (int i =0; i < 5; i++) {
            CAHomeUser * u = arr[i];
            [idArray addObject:u.userId];
        }

        [DBTool saveData:@{@"ForumIds":idArray} tag:@"ForumUsers"];
        
        NSMutableArray *array = [weakSelf getUserFormIdArray:idArray];
        
        success(array);
        
    } waitTime:0];
}


//用户绑定视频
+ (void)bindVideoToUser:(NSArray *)users sucess:(void(^)(void))success{
    NSArray * titles = @[
        @"Nature's Symphony: Serenade of Cascades 🌊",
        @"Embark on a Journey to Cascades 🏞️",
        @"Captivating Waters: Beauty of Falls 💦",
        @"Chasing Waterfalls: Adventure Awaits 🌿",
        @"Thundering Splendor: Power of Falls ⚡",
        @"Serenade of Cascades: Nature's Dance 💃",
        @"Marvels of Nature: Cascading Wonder 🌈",
        @"Whispers in the Wild: Peace by Falls 🍃"
    ];
    
   
    
    NSMutableArray * array = [NSMutableArray array];
    for (int i = 0; i< 8; i++) {
  
        NSString * path = [NSString stringWithFormat:@"CascadeRealmV/video/%d.mp4",i + 1];
        [array addObject:@{
            @"mediaPath":path,@"mediaType":@"video"
        }];
    }
    
    [Http postWithURL:mediaSearch params:array success:^(id  _Nonnull responseObject) {
        NSArray * arr = responseObject[@"data"];
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        for (NSDictionary *d in arr) {
            dic[d[@"mediaPath"]] = d;
        }
        
        for (int i = 0; i < users.count; i++) {
            CAHomeUser *u = users[i];
            u.videoIndex = i + 1;
            u.viodeTitle = titles[i];
            NSDictionary * d = dic[[NSString stringWithFormat:@"CascadeRealmV/video/%d.mp4",i + 1]];
            u.viodeUrl = d[@"mediaUrl"];
            u.viodeCover = d[@"thumbUrl"];
            [u save];
        }
        success();
        
    } failure:^(id  _Nonnull errObject) {
        
    }];
    
}


+ (void)getUserFormRequest:(NSMutableArray *)idArray userCount:(NSInteger)count success:(void(^)(NSArray *))success failure:(void(^)(void))failure{
    
    
    NSDictionary * dic = @{
        @"category":@"Popular",
        @"isPageMode":@1,
        @"isRemoteImageUrl":@1,
        @"limit":@"20",
        @"page":@"1",
        @"tag":@"All"
    };

    
    [Http postWithURL: wallSearch params:dic success:^(id  _Nonnull responseObject) {
        
        NSArray * dataArray = [CAHomeUser mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
        
        for (CAHomeUser * model in dataArray) {
            
            if([idArray containsObject:model.userId]){
                continue;
            }
            
            [idArray addObject:model.userId];
            [model save];
            
            if (idArray.count >= count) {
                success(idArray);
                break;
            }
        }
        
        if (idArray.count < count) {
            [self getUserFormRequest:idArray userCount:count success:success  failure:failure];
        }
        
        

    } failure:^(id  _Nonnull errObject) {
        
        failure();
        
    }];
    
}

+ (NSMutableArray *)getUserFormIdArray:(NSArray *)array{
    NSMutableArray *result = [NSMutableArray array];
    for (NSString * userId in array) {
        
        NSDictionary *dic = [DBTool getData:userId];
        CAHomeUser * user = [CAHomeUser mj_objectWithKeyValues:dic];
        [result addObject:user];
    }
    return result;
}


- (void)save{
    [DBTool saveData:self.mj_keyValues tag:self.userId];
}


- (void)SetIsVideolikeInDB:(BOOL)isVideolike{
    NSString * k = [NSString stringWithFormat:@"%@--isVideolike",CAUserInfo.shared.userInfo.userId];
    NSDictionary * dic = [DBTool getData:k];
    
    NSArray * arr = dic[@"isVideolike"];
    NSMutableArray * array = [NSMutableArray array];
    if (arr != nil) {
        array = [NSMutableArray arrayWithArray:arr];
    }
    
    if (isVideolike) {
        [array addObject:self.viodeTitle];
    }else{
        [array removeObject:self.viodeTitle];
    }
    
    [DBTool saveData:@{@"isVideolike":array} tag:k];
}



-(BOOL)isVideolike{
    NSDictionary * dic = [DBTool getData:[NSString stringWithFormat:@"%@--isVideolike",CAUserInfo.shared.userInfo.userId]];
    
    NSArray * arr = dic[@"isVideolike"];
   
    if (arr != nil && [arr containsObject:self.viodeTitle]) {
        return YES;
    }
    
    
    return NO;
}



@end
